#include "receive.h"
#include "stdio.h"
#include "userDriver.h"

PARAMETER_USART receive = {
  {0},0,USART_RECEIVE_STATE_IDLE
};

void RECEIVE_Get(uint8_t rxData)
{
  if(receive.RxState == USART_RECEIVE_STATE_IDLE && rxData == USART_RX_START_FLAG)
  {
    receive.RxState = USART_RECEIVE_STATE_START;
    receive.RxBufLen = 0;
  }
  else if(receive.RxState == USART_RECEIVE_STATE_START)
  {
    if(rxData == USART_RX_END_FLAG)
    {
      receive.RxState = USART_RECEIVE_STATE_DONE;
      receive.RxBuffer[receive.RxBufLen++] = '\0';
    }
    else
    {
      receive.RxBuffer[receive.RxBufLen] = rxData;
      if(receive.RxBufLen == USART_RX_BUFFER_LEN-2)
      {
        receive.RxState = USART_RECEIVE_STATE_OVER;
        receive.RxBuffer[receive.RxBufLen++] = '\0';
      }
      else
      {
        receive.RxBufLen++;
      }
    }
  }
  rxData = 0;
}

//void RECEIVE_Decoder(void)
//{
//  uint16_t temp = 0;
//  PARAMTER_PID *pid;
//  
//  if(receive.RxState == USART_RECEIVE_STATE_DONE)
//  {
//    if(receive.RxBuffer[0] == 'L')  pid = &pidL;
//    else if(receive.RxBuffer[0] == 'R')  pid = &pidR;
//    else
//    {
//      receive.RxState = USART_RECEIVE_STATE_IDLE;
//      return;
//    }
//    if(receive.RxBuffer[1] == 'K')
//    {
//      temp = receive.RxBuffer[3] - '0';
//      temp = temp*10 + receive.RxBuffer[4] - '0';
//      temp = temp*10 + receive.RxBuffer[5] - '0';
//      temp = temp*10 + receive.RxBuffer[6] - '0';
//      
//      printf("%hu\r\n", temp);
//      
//      if(receive.RxBuffer[2] == 'P')
//      {
//        pid->Kp = (float)temp/1000.0;
//      }
//      else if(receive.RxBuffer[2] == 'I')
//      {
//        pid->Ki = (float)temp/1000.0;
//      }
//      else if(receive.RxBuffer[1] == 'D')
//      {
//        pid->Kd = (float)temp/1000.0;
//      }
//    }
//    else if(receive.RxBuffer[1] == 'T')
//    {
//      pid->target = receive.RxBuffer[3] - '0';
//      pid->target = pid->target*10+receive.RxBuffer[4] - '0';
//      pid->target = pid->target*10+receive.RxBuffer[5] - '0';
//      if('-' == receive.RxBuffer[2])  pid->target = -pid->target;
//    }
//    receive.RxState = USART_RECEIVE_STATE_IDLE;
//  }
//  else if(receive.RxState == USART_RECEIVE_STATE_OVER)
//  {
//    receive.RxState = USART_RECEIVE_STATE_IDLE;
//  }
//  else if(receive.RxState == USART_RECEIVE_STATE_ERROR)
//  {
//    receive.RxState = USART_RECEIVE_STATE_IDLE;
//  }
//}


